package org.csu.myPetStore.web.servlet;

import org.csu.myPetStore.domain.Account;
import org.csu.myPetStore.domain.Item;
import org.csu.myPetStore.service.CatalogService;
import org.csu.myPetStore.service.LogcatService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;

public class ViewItemServlet extends HttpServlet {

    private static final String VIEW_ITEM = "/WEB-INF/jsp/catalog/Item.jsp";

    private String itemId;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        itemId = request.getParameter("itemId");
        CatalogService service = new CatalogService();
        Item item = service.getItem(itemId);
        HttpSession session = request.getSession();
        session.setAttribute("item",item);

        Account account = (Account) session.getAttribute("account");
        LogcatService logcatService = new LogcatService();

        java.util.Date date = new java.util.Date();
        Date datesql = new Date(date.getTime());
        if(account == null){
            logcatService.InsertLogCat(null, "Someone "  + " visit " + item.getProduct().getName() + " at " + datesql.toString());
        }else {
            logcatService.InsertLogCat(account.getUsername(),account.getUsername() + " visit " + item.getProduct().getName() + " at " + datesql.toString());
        }

        request.getRequestDispatcher(VIEW_ITEM).forward(request,response);
    }
}
